﻿using AiBLSmartEdu.Module.Role.API.DTOs;
using Application.Features.Groups.Repositories;
using AutoMapper;
using Domain.Entities;
using FrameworkCore.Constants;
using FrameworkCore.DI;
using FrameworkCore.Helpers;

namespace AiBLSmartEdu.Module.Role.API.Services;

/// <summary>
/// 角色服务
/// </summary>
public class RoleServices : IScopedDependency
{
    private readonly GroupServices _groupServices;
    private readonly IMapper _mapper;

    public RoleServices(GroupServices groupServices, IMapper mapper)
    {
        _groupServices = groupServices;
        _mapper = mapper;
    }

    /// <summary>
    /// 创建角色
    /// </summary>
    /// <param name="input">输入模型</param>
    /// <returns></returns>
    public async Task CreateAsync(CreateRoleInputModel input)
    {
        // 确保角色组存在
        var roleGroupId = await _groupServices.EnsureGroupExistsAsync(new Group
        {
            Groupname = GlobalConstants.GroupnameRole,
            Code = GlobalConstants.GroupCodeRole
        });

        // 映射输入模型并创建角色
        var group = _mapper.Map<Group>(input);
        group.ParentId = roleGroupId;
        await _groupServices.CreateAsync(group);
    }

    /// <summary>
    /// 修改角色
    /// </summary>
    /// <param name="input">输入模型</param>
    /// <returns></returns>
    public async Task UpdateAsync(UpdateRoleInputModel input)
    {
        var roleGroup = await _groupServices.GetAsync(input.Id, GlobalConstants.GroupnameRole, GlobalConstants.GroupCodeRole);
        ExceptionHelper.ThrowIfTrue(roleGroup == null, $"数据不存在");

        _mapper.Map(input, roleGroup);
        await _groupServices.UpdateAsync(roleGroup!);
    }
}
